package ar.com.msebuilder;

import java.util.LinkedList;

import org.tmatesoft.svn.core.wc.SVNRevision;

import ar.com.msebuilder.MSEBuilder.Operation;
import ar.com.msebuilder.SVNRevisionsFilter.SVNRevFilterTypes;

public class ThreadsManager {
	
	private String svnUrl;
	private String svnUser;
	private String svnPwd;
	private int currentRunningThreads=0;
	private int maxTrheads=0;
	private boolean deleteSVNFiles;
	private Operation operation;
	
	public ThreadsManager(String svnUrl, String svnUser, String svnPwd, int threadsNum, 
			boolean deleteSVNFiles, Operation operation) {
		this.svnUrl = svnUrl;
		this.svnUser = svnUser;
		this.svnPwd = svnPwd;
		this.maxTrheads = threadsNum;
		this.deleteSVNFiles = deleteSVNFiles;
		this.operation = operation;
	}

	public void downloadRevisionsAndCreateMSEFiles(long minRevision, 
			long maxRevision, String svnDestPath, SVNRevFilterTypes svnFilter, 
			String mseDestPath) {
		// Parse the revisions list depending on the filter chosen by the user
		SVNRevisionsFilter svnRevFilter = new SVNRevisionsFilter(
				new SVNManager(svnUrl, svnUser, svnPwd).getSVNRepository(), 
				minRevision, maxRevision);
		LinkedList<SVNRevision> revisionsList = svnRevFilter.parseRevisionsList(svnFilter);
		// Download the revisions
		for (SVNRevision revision : revisionsList) {
			// Add 1 to the number of current threads running 
			// (or wait if they are all running)
			addRunningThreads();
			// Download the revision from the SVN repository and create the MSE file
			// A new SVNManager has to be created for every thread
			new SVNCheckoutThread(this, new SVNManager(svnUrl, svnUser, svnPwd), 
					svnDestPath + "/" + revision.getNumber(), revision, 
					mseDestPath, deleteSVNFiles, operation).start();
		}
	}
	
	public synchronized int getCurrentRunningThreads() {
		return currentRunningThreads;
	}

	public synchronized void addRunningThreads() {
		if(currentRunningThreads>=maxTrheads)
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		currentRunningThreads++;
	}
	
	public synchronized void removeRunningThreads() {
		currentRunningThreads--;
		notify();
	}

}